# 用户相关视图
import json
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt

# log response
from tanxi.client.Handler.Logger import log_info, log_error
from tanxi.client.Handler.JsonResponse import create_response

# 数据库类型 选择
from django.conf import settings
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.client.utils.mysql.users_mysql import UserHandler
elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.client.utils.sqlite.users_sqlite import UserHandler
else:
    raise ValueError("Unsupported database type specified in settings.")


# 类功能初始化
user = UserHandler()

# 用户 注册 登录
@require_POST
@csrf_exempt
def user_login(request):
    data = json.loads(request.body)
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    log_info(f"用户登录请求: {username}, {password}, {email}")
    if not username or not password:
        log_error(f"用户名或密码不能为空: {username}, {password}")
        return create_response(code=400, message="Error", remarks="用户名或密码不能为空", data=[])
    
    result = user.user_login(username, password, email)
    # 假设 result 中包含了 token 和 user_id
    log_info(f"结果{result}")
    response_data = {
        "status": "success",
        "message": result["login_message"],
        "token": result["token"],  # 确保后端生成了token
        "username": username,
        "user_id": result['user_id']  # 确保后端生成了user_id
    }

    cookies = {
        "user_id": {
            "value": result['user_id'],
            "max_age": 3600 * 24 * 1,  
            "httponly": True,
            "secure": True,
            "samesite": "Lax"
        },
        "token": {  # 添加token到cookie
            "value": result['token'],
            "max_age": 3600 * 24 * 1,
            "httponly": True,
            "secure": True,
            "samesite": "Lax"
        }
    }

    return create_response(
        code=200, 
        message="Success", 
        remarks="登录成功",
        data=response_data,  # 返回包含token的数据
        cookies=cookies
    )

# 用户 信息获取 按user_id获取/获取所有
@require_GET
@csrf_exempt
def user_info(request):
    user_id = request.GET.get('user_id')
    log_info(f"用户信息获取请求: {user_id}")
    # 单个用户信息
    if user_id:
        data = user.get_user_info(int(user_id))
        return create_response(code=200, message="Success", remarks="用户信息获取成功", data=data)
    
    # 所有用户信息
    else:
        data = user.get_user_info()
        return create_response(code=200, message="Success", remarks="用户信息获取成功", data=data)



# 用户 更新 
@require_POST
@csrf_exempt
def user_update(request):
    # json
    data = json.loads(request.body)
    log_info(f"用户更新请求: {data}")
    info = user.update_user_info(data)
    # 用户信息字典
    if info:
        return create_response(code=200, message="Success", remarks="用户信息更新成功", data=[])
    else:
        return create_response(code=400, message="Error", remarks="用户信息更新失败", data='该用户未注册')


# 用户 删除
@require_GET
@csrf_exempt
def user_delete(request):
    user_id = request.GET.get('user_id')
    # 删除用户
    info = user.delete_user(user_id)    
    if info:    
        return create_response(code=200, message="Success", remarks="用户信息删除成功", data='删除成功')
    else:
        return create_response(code=400, message="Error", remarks="用户信息删除失败", data='删除失败')

